import {service, wxapi} from '../../api';
const app = getApp()

Page({
    data: {
        isshownone:false,
        condition:{},
        tabCondition:[],
        current:-1,
        popLeft:[{name:'区域'},{name:'地铁'}],
        popRight:[],
        popup:true,
        param:{page:1,orderby:'distance',hot:true},
        pageNum:1,
        total:0,
        location:['location','',''],
        tabs:['location','area','price','format'],
        list:[],
        inputValue:'',
        platform:'IOS',
        rigth:'padding:0rpx 0rpx 20rpx 30rpx ;'
    },
    onLoad: function () {

        this.getList();

        service.getCriteria((res)=>{
            console.log(res)
            if(res.statusCode < 400){
                this.initPageData(res.data.data)
                // this.setData({
                //     condition: res.data.data
                // })
            }else{
                console.log('getList fail')
            }


        })
      this.checkModel();
    },
    tolower(){
        var pageNum = this.data.pageNum;
        var total = this.data.total;
        var list = this.data.list;
        if(total && list.length < total){
            pageNum ++ ;
            this.setData({
                pageNum : pageNum
            })
            this.getList(1)
        }


    },
    clearText:function(){
      //debugger
      var param = this.data.param;
      param.keyword='';
      this.setData({
        inputValue:'',
        param: param
      });
      this.getList();
    },
    getList(tag){
      //tag 1 滚动加载
      this.setData({
        isshownone: false
      })
      wx.showLoading({title:'加载中...'})
        var param = this.data.param;
        var list = this.data.list;
        var pageNum = this.data.pageNum;
        param.page = pageNum;
        wxapi.getLocation((res)=>{
            if(res){
                param.lat =  res.latitude
                param.lng =  res.longitude
            }
            //param.lat = 31.36185;
            //param.lng = 120.607352;
            service.getList(param,(res)=>{
                if(res.statusCode < 400){
                    this.setData({
                        total : res.data.total,
                        list: tag ? [...list, ...res.data.data] : res.data.data
                    })
                }else{
                    console.log('getList fail')
                }
                wx.hideLoading();
                if (this.data.list.length==0){
                  this.setData({
                    isshownone:true
                  })
                }else{
                  this.setData({
                    isshownone: false
                  })
                }
            })
        })
    },
    initPageData(data){

        for(var i in data){
          var temp = []
          if(i != 'location'){
            data[i].forEach((item,idx)=>{
                temp.push({name:item,select:idx == 0?1:0})
            })
            data[i] = temp;
          }else{
              for(var j in data[i]){//j : districts subways
                for(var k in data[i][j]){
                  var temp1 = []
                    k == 0 && (data[i][j][k].select =1);
                    if(data[i][j][k]['commercialareas'] && data[i][j][k]['commercialareas'].length > 0){
                        for(var g in data[i][j][k]['commercialareas']){
                            temp1.push({name:data[i][j][k]['commercialareas'][g],select:g == 0?1:0})
                        }
                        data[i][j][k]['commercialareas'] = temp1;
                    }
                    if(data[i][j][k]['stations'] && data[i][j][k]['stations'].length > 0){
                        for(var g in data[i][j][k]['stations']){
                            temp1.push({name:data[i][j][k]['stations'][g],select:g == 0?1:0})
                        }
                        data[i][j][k]['stations'] = temp1;
                    }



                }
              }
          }
        }

       this.setData({
           condition:data,
           tabCondition:[
               {
                 popLeft:[{name:'区域',select:1},{name:'地铁'}],
                 popRight:data.location.districts
               },
               {
                   popLeft:[],
                   popRight:data.area
               },
               {
                   popLeft:[],
                   popRight:data.price
               },
               {
                   popLeft:[],
                   popRight:data.format
               }],
           popLeft:  [{name:'区域',select:1},{name:'地铁'}],
           popRight: data.location.districts
       })
    },
    confirm(e){
      var value = e.detail.value;
      var param = this.data.param;
        value = value.replace(/^\s*/g,'').replace(/\s*$/g,'')
      if(!value){
          wx.showToast({
              title: '搜索词不能为空',
              icon: 'none',
              duration: 1000
          })
          return;
      }
      param.keyword = value;
      this.setData({param:param})
      this.getList();
    },
    leftBind(e){
      let index = e.currentTarget.dataset.index;
      let popLeft = this.data.popLeft
      let current = this.data.current
      let location = this.data.location

      let tabCondition = this.data.tabCondition
      let leftObj = popLeft[index]
        let rightData = [];
       if(leftObj.name == '区域'){
           rightData = this.data.condition.location.districts
           location[0] = 'location'
       }
       if(leftObj.name == '地铁'){
           rightData = this.data.condition.location.subways
           location[0] = 'subway'
       }
        if(leftObj.name == '不限'){
            popLeft.forEach((item, idx) => {
                if (idx == index) {
                    item.select = 1;
                } else {
                    item.select = 0;
                }
            })
            rightData = popLeft
            if(location[0] == 'location'){
               popLeft = [{name:'区域',select:1},{name:'地铁'}]
            }
            if(location[0] == 'subway'){
               popLeft = [{name:'区域'},{name:'地铁',select:1}]
            }
            location[1] = ''

        }
       if(leftObj.commercialareas && leftObj.commercialareas.length > 0){
           rightData = leftObj.commercialareas
           location[1] = leftObj.name
       }
       if(leftObj.stations && leftObj.stations.length > 0){
           rightData = leftObj.stations
           location[1] = leftObj.name
       }
 //...
        if(leftObj.name != '不限') {
            popLeft.forEach((item, idx) => {
                if (idx == index) {
                    item.select = 1;
                } else {
                    item.select = 0;
                }
            })
        }

        tabCondition[current].popLeft = popLeft
        tabCondition[current].popRight = rightData
      this.setData({
          tabCondition: tabCondition,
          location:location,
          popLeft:popLeft,
          popRight:rightData
      })

    },
    rightBind(e){
        let index = e.currentTarget.dataset.index;
        let popLeft = this.data.popLeft
        let condition = this.data.condition
        let current = this.data.current
        let location = this.data.location
        let popRight = this.data.popRight
        let param = this.data.param
        let tabs = this.data.tabs
        let tabCondition = this.data.tabCondition
        let rightObj = popRight[index]

        if(current == 0) {
            let rightArr = (rightObj.commercialareas || rightObj.stations || []);
            if(rightArr.length == 0){
                location[2] = rightObj.name;
                if(location[0] == 'location'){
                    param.location = `${location[1]?(location[1]+'-'):''}${location[2]}`
                }else{
                    delete  param.location;
                }
                if(location[0] == 'subway'){
                    param.subway = `${location[1]?(location[1]+'-'):''}${location[2]}`
                }else{
                    delete  param.subway;
                }
                for(var i in popRight){
                    if(i == index){
                        popRight[i].select = 1;
                    }else{
                        popRight[i].select = 0;
                    }
                }
                tabCondition[current].popLeft = popLeft
                tabCondition[current].popRight = popRight
                this.setData({
                    popup:true,
                    tabCondition :tabCondition ,
                    location:location,
                    current: -1,
                    param :param,
                    popLeft: popLeft,
                    popRight: popRight
                })

                this.getList();
            }else{
                location[1] = rightObj.name;
                tabCondition[current].popLeft =  popRight
                tabCondition[current].popRight = rightArr
                if(location[0] == 'location'){
                    param.location = `${location[1]?(location[1]+'-'):''}${location[2]}`
                }else{
                    delete  param.location;
                }
                if(location[0] == 'subway'){
                    param.subway = `${location[1]?(location[1]+'-'):''}${location[2]}`
                }else{
                    delete  param.subway;
                }
                for(var i in popRight){
                    if(i == index){
                        popRight[i].select = 1;
                    }else{
                        popRight[i].select = 0;
                    }
                }
                this.setData({
                    tabCondition :tabCondition ,
                    location:location,
                    popLeft: popRight,
                    param : param,
                    popRight: rightArr
                })
            }
            // location 姑苏区-平江新城万达商圈  subway 2号线-

        }else{

            for(var i in popRight){
               if(index == i){
                   popRight[i].select = 1
               }else{
                   popRight[i].select = 0
               }
            }
            tabCondition[current].popLeft = []
            tabCondition[current].popRight = popRight;
            var param_copy = {...param}
            if(current == 1 && index > 0){
                param.area = rightObj.name;
            }else if(current == 1 && index == 0){
                delete param.area;
            }
            if(current == 2 && index > 0){
                param.price = rightObj.name;
            }else if(current == 2 && index == 0) {
                delete param.price;
            }
            if(current == 3 && index > 0){
                param.format = rightObj.name;
            }else if(current == 3 && index == 0){
                delete param.format;
            }
                // current =  -1;


            this.setData({
                tabCondition :tabCondition ,
                param :param,
                current:-1,
                pageNum:1,
                popup:true,
                popLeft: [],
                popRight: popRight
            });

            (index > 0 || param_copy[tabs[current]])  && this.getList();
        }


    },
    selectTab(e){
      let index = e.currentTarget.dataset.index;
      let popLeft = [],popRight = [];
      let condition = this.data.condition
      let tabCondition = this.data.tabCondition
      let current = this.data.current

      switch(~~index){
          case 0:
              popLeft = condition.popLeft
              popRight = condition.popRight
            break;
          case 1:
              popRight = condition.area
              popLeft = []
            break;
          case 2:
              popRight = condition.price
              popLeft =[]
            break;
          case 3:
              popRight = condition.format
              popLeft =[]
            break;
      }

      this.setData({
          popup:current == index ? true :false,
          current:current == index ? -1 :index,
          condition:condition,
          popLeft:tabCondition[index].popLeft,
          popRight:tabCondition[index].popRight,
      })
    },
    cancelPop(){
        this.setData({
            popup: true,
            current: -1
        })
    },
    select(e){
      var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/detail/detail?id=${id}`
        })
    },
    checkModel: function () {
      var that = this;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            systemInfo: res,
          })
          if (res.platform == "devtools") {
            //PC
          } else if (res.platform == "ios") {
            //IOS
            that.setData({
              platform: res.platform,
              rigth: 'padding:30rpx 0rpx 20rpx 30rpx ;'
            })
          } else if (res.platform == "android") {
            //android
            that.setData({
              platform: res.platform,
              rigth:'padding:0rpx 0rpx 20rpx 30rpx ;'
            })
          }
        }
      })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
